package cn.itcast.controller;

import cn.itcast.entity.MessageConstant;
import cn.itcast.entity.PageResult;
import cn.itcast.entity.QueryPageBean;
import cn.itcast.entity.Result;
import cn.itcast.pojo.Company;
import cn.itcast.service.CompanyService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 公司地址管理
 */
@RestController
@RequestMapping("company")
public class CompanyController {

    @Reference
    private CompanyService companyService;

    //获取所有的公司地址集合
    @RequestMapping("/getAddress.do")
    public Result getAddress() {

        try {
            List<Company> list = companyService.findAll();
            return new Result(true, MessageConstant.GET_COMPANY_ADDRESS_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_COMPANY_ADDRESS_FAIL);
        }
    }

    //分页查询公司地址
    @RequestMapping("/findPage.do")
    public Result findPage(@RequestBody QueryPageBean queryPageBean) {

        try {
            PageResult pageResult = companyService.findPage(queryPageBean);
            return new Result(true, MessageConstant.GET_COMPANY_ADDRESS_SUCCESS,pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_COMPANY_ADDRESS_FAIL);
        }
    }

    //添加公司地址
    @RequestMapping("/add.do")
    public Result add(@RequestBody Company company) {

        try {
            //1 先查询
            Company company1 = companyService.findByAddress(company.getAddress_name());
            if (company1==null) {
                //2 不是重复添加，继续操作
                companyService.add(company);
                return new Result(true, MessageConstant.ADD_COMPANY_ADDRESS_SUCCESS);
            }
            return new Result(false, MessageConstant.ADD_COMPANY_ADDRESS_REPEAT);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_COMPANY_ADDRESS_FAIL);
        }
    }

    //删除公司地址
    @RequestMapping("/delete.do")
    public Result delete(int id) {

        try {
            companyService.deleteById(id);
            return new Result(true, MessageConstant.DELETE_COMPANY_ADDRESS_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.DELETE_COMPANY_ADDRESS_FAIL);
        }
    }

}
